import router from '@/routers/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { getUrlParamsKey } from '@/utils/tools'
import { dinglogin } from '@/utils/database'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/auth-redirect'] // 设置白名单
// 记录路由
let hasRoles = true

router.beforeEach(async (to, from, next) => {
  // 开启进度条
  NProgress.start()
  // 设置标题
  if (typeof to.meta.title === 'string') {
    document.title = to.meta.title || '农服管理平台'
  }
  NProgress.done()
  /**
   * 如果store里面没有token那么且链接后面存在token就更新token，
   * 否则不更新
   */
  const token = getUrlParamsKey('token') || ''
  const UserStore = useUserStore()
  console.log(import.meta.env.VITE_IS_NEED_LOGIN)
  if (import.meta.env.VITE_IS_NEED_LOGIN) {
    const chulitoken = (token) => {
      const astr = token.split('.')
      if (astr.length > 0) {
        const userinfo = JSON.parse(decodeURIComponent(escape(window.atob(astr[1].replace(/-/g, '+').replace(/_/g, '/')))))
        const data = JSON.parse(userinfo.sub)
        if (data?.name) {
          UserStore.userInfo.username = data?.name
        } else {
          UserStore.userInfo.username = 'adminW'
        }
      }
    }
    if (token.length > 0) {
      UserStore.token = token
      chulitoken(token)
    }
    // 确定用户是否已登录过，存在Token
    const hasToken = UserStore.token

    if (hasToken) {
      if (to.path === '/login') {
        // 如果已登录，请重定向到主页
        next({ path: '/' })
      } else {
        try {
          const PermissionStore = usePermissionStore()
          // 路由添加进去了没有及时更新 需要重新进去一次拦截
          if (!PermissionStore.routes.length) {
            // 获取权限列表进行接口访问 因为这里页面要切换权限
            const accessRoutes = await PermissionStore.generateRoutes(UserStore.roles)
            hasRoles = false
            ;(accessRoutes as any).forEach((item) => router.addRoute(item)) // 动态添加访问路由表
            next({ ...to, replace: true }) // // 这里相当于push到一个页面 不在进入路由拦截
          } else {
            next() // // 如果不传参数就会重新执行路由拦截，重新进到这里
          }
        } catch (error) {
          next(`/login?redirect=${to.path}`)
        }
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        UserStore.token = ''
        next()
        // dinglogin()
        // next(`/login?redirect=${to.path}`)
      }
    }
  } else {
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})
